package controller

import (
	"context"
	"embed"
	"godesk/app/model"
	"godesk/app/util"
	"time"

	"github.com/wailsapp/wails/v2/pkg/application"
	"github.com/wailsapp/wails/v2/pkg/options"
	"github.com/wailsapp/wails/v2/pkg/options/assetserver"
	"github.com/wailsapp/wails/v2/pkg/options/linux"
	"github.com/wailsapp/wails/v2/pkg/options/mac"
	"github.com/wailsapp/wails/v2/pkg/options/windows"
)

// WailsRun 初始化
func WailsRun(assets embed.FS, port int, icon []byte, wIcon []byte) {
	// 创建控制器实例
	system := NewSystem()
	config := NewConfig()
	server := NewServer()
	wallpaper := NewWallpaper()
	audio := NewAudio()
	photo := NewPhoto()
	weather := NewWeatherService()
	rili := NewRili()
	memo := NewMemoApp()
	note := NewNote()
	TimestampConverter := NewTimestampConverter()
	json := NewJSONApp()
	screenShot := NewScreenApp()

	//应用实例
	app := application.NewWithOptions(&options.App{
		Title:  "洛页小工具",
		Width:  900,
		Height: 650,
		AssetServer: &assetserver.Options{
			Assets: assets,
		},
		Frameless:        false,
		BackgroundColour: &options.RGBA{R: 255, G: 255, B: 255, A: 1},
		//启动时回调
		OnStartup: func(ctx context.Context) {
			//设置 context 对象
			system.setCtx(ctx)
			config.setCtx(ctx)
			server.setCtx(ctx)
			audio.setCtx(ctx)
			photo.setCtx(ctx)
			wallpaper.setCtx(ctx)
			weather.setCtx(ctx)
			rili.setCtx(ctx)
			memo.setCtx(ctx)
			note.setCtx(ctx)
			TimestampConverter.setCtx(ctx)
			json.setCtx(ctx)
			screenShot.setCtx(ctx)

			//启动自定义服务，初始化数据表
			server.start(port).log("程序已启动").schema(&model.Config{}, &model.Note{}, &model.Category{})
		},
		Bind: []interface{}{
			system,
			config,
			server,
			wallpaper,
			audio,
			photo,
			weather,
			rili,
			memo,
			note,
			TimestampConverter,
			json,
			screenShot,
		},
		Mac: &mac.Options{
			TitleBar: mac.TitleBarDefault(),
			About: &mac.AboutInfo{
				Title:   "洛页小工具",
				Message: "洛页小工具",
				Icon:    icon,
			},
			WebviewIsTransparent: false,
			WindowIsTranslucent:  false,
		},
		Windows: &windows.Options{
			WebviewIsTransparent:              false,
			WindowIsTranslucent:               false,
			DisableFramelessWindowDecorations: true,
		},
		Linux: &linux.Options{
			ProgramName:         "洛页小工具",
			Icon:                icon,
			WebviewGpuPolicy:    linux.WebviewGpuPolicyOnDemand,
			WindowIsTranslucent: false,
		},
	})

	//设置托盘
	go func() {
		util.NewSystrayUtil(wIcon, &system.ctx, app).Run()
	}()

	//初始化数据库
	go func() {
		time.Sleep(time.Second * 3)
		util.NewDbUtil(&system.ctx).Run()
	}()

	// 启动wails服务
	err := app.Run()
	if err != nil {
		println("Error:", err.Error())
	}
}
